$(document).ready(function() {
	var OpeoutObj="";
    var VAL ={
        NORMAL     : "0000000"  ,
        EVT_USER   : $("#userId").text(),
        T_XPINQBOX  : "XPINQBOX",
        T_XPBISTOL  : "XPBISTOL",
        T_XPWIPBANK  : "XPWIPBANK",
        T_XPBISOPE  : "XPBISOPE"
    };
    /**
     * All controls's jquery object/text
     * @type {Object}
     */
    var controlsQuery = {
        W                 : $(window)              ,
        ppBoxIDInput      : $("#ppBoxIDInput")     ,
        wipBankSelect     : $("#wipBankSelect")    ,
        grdLegendDiv      : $("#grdLegendDiv")     ,
        lotIdInput        : $("#lotIdInput")       ,  

        mainGrd   :{
            grdId     : $("#boxDetailGrd")   ,
            grdPgText : "#boxDetailPg"       ,
            fatherDiv : $("#boxDetailDiv")
        }
    };

    /**
     * All button's jquery object
     * @type {Object}
     */
    var btnQuery = {
        query : $("#query_btn"),
        bank_out : $("#bank_out_btn"),
        bank_in  : $("#bank_in_btn")
    };

    /**
     * All tool functions
     * @type {Object}
     */
    var toolFunc = {
//        resetJqgrid :function(){
//            controlsQuery.W.unbind("onresize");
//            controlsQuery.mainGrd.grdId.setGridWidth(controlsQuery.mainGrd.fatherDiv.width()*0.90);
//            controlsQuery.W.bind("onresize", this);
//        },
        clearInput : function(){
            controlsQuery.ppBoxIDInput.val("");
        },
        iniWipBankSelect : function(){
            var inObj,
                outObj,
                tool_cnt,
                tool_ary = [];

            inObj = {
                trx_id      : VAL.T_XPBISTOL,
                action_flg  : 'Q'           ,
                iary        : {
                    tool_cate: 'WPBK'
                }
            };
            outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                _setSelectDate(outObj.tbl_cnt, outObj.oary, 'tool_id', 'tool_id', '#wipBankSelect' ,true);
            }
        },
        /**
         * 根据人员，厂别，站点的关系，筛选出可以使用的站点。By CMJ
         */
        iniOpeSelect : function(){
            var inObj;
            var user_id = VAL.EVT_USER;
            var iaryB = {
                user_id     : user_id
            }
            inObj = {
                trx_id      : VAL.T_XPBISOPE,
                action_flg  : 'I',
                iaryB       : iaryB
            };
            OpeoutObj = comTrxSubSendPostJson(inObj);
        }
    };

    /**
     * All button click function
     * @type {Object}
     */
    var btnFunc = {
        //Query
        query_func : function(){
            var inObj,
                outObj,
                box_id,
                tool_id;

            inObj = {
                trx_id : VAL.T_XPINQBOX,
                action_flg : 'C',
                bnk_flg    : '1',
                box_stat   : 'WAIT'
            };

            tool_id = controlsQuery.wipBankSelect.val().trim();
            if(tool_id){
                inObj.tool_id = tool_id;
            }

            box_id = controlsQuery.ppBoxIDInput.val().trim();
            if(box_id){
                inObj.box_id = box_id;
            }
            
            lot_id = controlsQuery.lotIdInput.val().trim();
            if (lot_id) {
				inObj.lot_id = lot_id;
			}

            outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
            	controlsQuery.mainGrd.grdId.clearGridData();
            	/**
    		     * 检查用户是否有权限操作这个箱子。By CMJ
    		     */
            	if(outObj.box_cnt>0){
            		if(box_id){
            			for(var i=0;i<OpeoutObj.tbl_cnt;i++){
            		    	var Opeoary = OpeoutObj.tbl_cnt>1 ? OpeoutObj.oary[i] : OpeoutObj.oary;
            		    	if($.trim(outObj.table.nx_ope_id_fk) == Opeoary.ope_id && 
            		    	   $.trim(outObj.table.nx_ope_ver_fk) == Opeoary.ope_ver){
            		    		setGridInfo(outObj.table, "#boxDetailGrd");
            	                controlsQuery.ppBoxIDInput.val("");
            	                break;
            		    	}
                		}
                		if(OpeoutObj.tbl_cnt==0 || i>=OpeoutObj.tbl_cnt){
            		    	showErrorDialog("", "此用户没有权限操作站点["+outObj.table.nx_ope_id_fk+"]的箱子！");
            			    return false; 
            		    }
            		}else{
            			for(var j=0;j<outObj.box_cnt;j++){
            				var boxTable = outObj.box_cnt>1?outObj.table[j]:outObj.table;
            				for(var i=0;i<OpeoutObj.tbl_cnt;i++){
                		    	var Opeoary = OpeoutObj.tbl_cnt>1 ? OpeoutObj.oary[i] : OpeoutObj.oary;
                		    	if($.trim(boxTable.nx_ope_id_fk) == Opeoary.ope_id && 
                		    	   $.trim(boxTable.nx_ope_ver_fk) == Opeoary.ope_ver){
                		    		controlsQuery.mainGrd.grdId.jqGrid('addRowData', j, {
                		    			box_id        : boxTable.box_id,
                		    			box_stat      : boxTable.box_stat,
                		    			tool_id_fk    : boxTable.tool_id_fk,
                		    			lot_id_fk     : boxTable.lot_id_fk,
                		    			wo_id_fk      : boxTable.wo_id_fk,
                		    			nx_path_id_fk : boxTable.nx_path_id_fk,
                		    			nx_ope_id_fk  : boxTable.nx_ope_id_fk,
                		    			prd_qty       : boxTable.prd_qty
                                    });
                		    	}
                    		}
            			}
            		}
            	}
            }
        },
        //Bank out
        bank_out_func : function(){
            //T_XPWIPBANK
            var i,
                inObj,
                outObj,
                box_id,
                crGrid,
                rowIds,
                idLen,
                curRowData,
                iary = [];

            crGrid = controlsQuery.mainGrd.grdId;
            rowIds = crGrid.jqGrid('getGridParam','selarrrow');
            if(rowIds.length === 0 ){
                showErrorDialog("","请先勾选需要返回产线的箱号！");
                return false;
            }

            idLen = rowIds.length;
            for( i=0; i < idLen; i++){
                curRowData = crGrid.jqGrid('getRowData', rowIds[i]);
                iary.push({
                    box_id : curRowData['box_id']
                });
            }

            inObj = {
                trx_id     : VAL.T_XPWIPBANK ,
                action_flg : 'O',
                evt_usr    : VAL.EVT_USER,
                box_cnt    : idLen       ,
                iary       : iary
            };
            outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                showSuccessDialog("返回产线成功");
                btnFunc.query_func();
            }

            return true;
        },
        //Bank in
        bank_in_func : function(){
            var inObj,
                outObj,
                box_id,
                tool_id;

            box_id = controlsQuery.ppBoxIDInput.val().trim();
            if(!box_id){
                showErrorDialog('','请输入箱号！');
                return false;
            }
            /**
		     * 检查用户是否有权限操作这个箱子。By CMJ
		     * Start
		     */
            var inTrx = {
    		    trx_id     : VAL.T_XPINQBOX,
    		    action_flg : "Q"    ,
    		    box_id     : box_id
    		};
            var outTrx = comTrxSubSendPostJson(inTrx);
            if(outTrx.rtn_code == VAL.NORMAL){
            	if(outTrx.box_stat == "WAIT"){
            		for(var i=0;i<OpeoutObj.tbl_cnt;i++){
        		    	var Opeoary = OpeoutObj.tbl_cnt>1 ? OpeoutObj.oary[i] : OpeoutObj.oary;
        		    	if($.trim(outTrx.nx_ope_id_fk) == Opeoary.ope_id && 
        		    	   $.trim(outTrx.nx_ope_ver_fk) == Opeoary.ope_ver){
        		    		break;
        		    	}
            		}
            		if(OpeoutObj.tbl_cnt==0 || i>=OpeoutObj.tbl_cnt){
        		    	showErrorDialog("", "此用户没有权限操作站点["+outTrx.nx_ope_id_fk+"]的箱子！");
        			    return false; 
        		    }
            	}
            }
            //<--End
            tool_id = controlsQuery.wipBankSelect.val().trim();
            if(!tool_id){
                showErrorDialog('','请选择在制仓！');
                return false;
            }

            inObj = {
                trx_id : VAL.T_XPWIPBANK,
                action_flg : 'I',
                evt_usr    : VAL.EVT_USER,
                box_id     : box_id      ,
                tool_id    : tool_id
            };

            outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                showSuccessDialog("转入在制仓成功");
                btnFunc.query_func();
            }
        }
    };

    /**
     * Bind button click action
     */
    var iniButtonAction = function(){
        btnQuery.query.click(function(){
            btnFunc.query_func();
        });
        btnQuery.bank_out.click(function(){
            btnFunc.bank_out_func();
        });
        btnQuery.bank_in.click(function(){
            btnFunc.bank_in_func();
        });
    };

    /**
     * grid  initialization
     */
    var iniGridInfo = function(){
        var grdInfoCM = [
            {name: 'box_id',        index: 'box_id',        label: BOX_ID_TAG  , width: BOX_ID_CLM},
            {name: 'box_stat',      index: 'box_stat',      label: STATUS_TAG ,  width: PRD_STAT_CLM},
            {name: 'tool_id_fk',    index: 'tool_id_fk',    label: DFT_WIP_BANK_TOOL_ID_TAG ,  width: TOOL_ID_CLM},
            {name: 'lot_id_fk',     index: 'lot_id_fk',     label: LOT_ID_TAG ,  width: LOT_ID_CLM},
            {name: 'wo_id_fk',      index: 'wo_id_fk',      label: WO_ID_TAG ,   width: WO_ID_CLM},
            {name: 'nx_path_id_fk', index: 'nx_path_id_fk', label: PATH_ID_TAG , width: PATH_ID_CLM},
            {name: 'nx_ope_id_fk',  index: 'nx_ope_id_fk',  label: OPE_ID_TAG ,  width: OPE_ID_CLM},
            {name: 'prd_qty',  index: 'prd_qty',  label: "玻璃数量" ,  width: OPE_ID_CLM}
        ];
        controlsQuery.mainGrd.grdId.jqGrid({
            url:"",
            datatype:"local",
            mtype:"POST",
            height:300,
            width:600,
            shrinkToFit:false,
            scroll:true,
            rownumWidth : true,
            resizable : true,
            rowNum:40,
            loadonce:true,
            fixed:true,
            viewrecords:true,
            multiselect : true,
            pager : controlsQuery.mainGrd.grdPgText,
            colModel: grdInfoCM
        });
     };

    var shortCutKeyBind = function(){
        document.onkeydown = function(event) {
            if(event.keyCode == F1_KEY){
                btnQuery.bank_out.click();
                return false;
            }else if(event.keyCode == F2_KEY){
                btnQuery.bank_in.click();
                return false;
            }

            return true;
        };
    };

    /**
     * Other action bind
     */
    var otherActionBind = function(){
        // Reset size of jqgrid when window resize
//        controlsQuery.W.resize(function(){
//            toolFunc.resetJqgrid();
//        });

        //Stop from auto commit
        $("form").submit(function(){
            return false;
        });

        controlsQuery.ppBoxIDInput.keydown(function(event){
            if(event.keyCode === 13){
                btnFunc.query_func();
            }
        });
        
        controlsQuery.lotIdInput.keydown(function(event){
            if(event.keyCode === 13){
                btnFunc.query_func();
            }
        });
    };

    /**
     * Ini contorl's data
     */
    var iniContorlData = function(){
        toolFunc.clearInput();
        toolFunc.iniWipBankSelect();
        toolFunc.iniOpeSelect();
    };

    /**
     * Ini view, data and action bind
     */
    var initializationFunc = function(){
        iniGridInfo();
        iniButtonAction();
        otherActionBind();

//        toolFunc.resetJqgrid();

        iniContorlData();
    };

    initializationFunc();
    function resizeFnc(){  
    	comResize(controlsQuery.W,controlsQuery.mainGrd.fatherDiv,controlsQuery.mainGrd.grdId);
    };                                                                                         
    resizeFnc();                                                                               
    controlsQuery.W.resize(function() {                                                         
    	resizeFnc();                                                                             
	});       
});

